package com.cytech.cloudclinic.moudle.main.drug.add.base;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.cytech.cloudclinic.R;
import com.cytech.cloudclinic.adapter.AddDrugTagAdapter;
import com.cytech.cloudclinic.adapter.AddDrugTagMulAdapter;
import com.cytech.cloudclinic.base.BaseFragment;
import com.cytech.cloudclinic.bean.AddDrugTag;
import com.cytech.cloudclinic.bean.DrugTag;
import com.cytech.cloudclinic.bean.event.UpdateAddTagEvent;
import com.cytech.cloudclinic.bean.req.AddDrugReq;
import com.cytech.cloudclinic.bean.resp.RespDrugDetail;
import com.cytech.cloudclinic.dialog.AddDrugTagDialog;
import com.cytech.cloudclinic.moudle.main.drug.add.AddDrugActivity;
import com.cytech.cloudclinic.moudle.main.drug.add.dosage.AddDrugDosageFragment;
import com.cytech.cloudclinic.moudle.main.drug.add.dosage.AddDrugDosageView;
import com.cytech.cloudclinic.utils.ConvertUtils;
import com.sly.pylibrary.Cn2Py;
import com.yechaoa.yutils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.cytech.cloudclinic.app.Constant.MODE_PACKAGE_ID;
import static com.cytech.cloudclinic.app.Constant.MODE_TAG_ID;

public class AddDrugBaseFragment extends BaseFragment<AddDrugBasePresenter> implements AddDrugBaseView {
    @BindView(R.id.rv_add_drug_tag)
    RecyclerView recyclerView;
    @BindView(R.id.et_add_drug_qr_code)
    EditText etAddDrugQrCode;
    @BindView(R.id.et_add_drug_name)
    EditText etAddDrugName;
    @BindView(R.id.et_add_drug_qr_name_py)
    EditText etAddDrugQrNamePy;
    @BindView(R.id.et_add_drug_qr_factory)
    EditText etAddDrugQrFactory;
    @BindView(R.id.et_add_drug_package_price)
    EditText etAddDrugPackagePrice;
    @BindView(R.id.et_add_drug_min_price)
    EditText etAddDrugMinPrice;
    private int drugTagId;
    private int drugId;
    private int parentDrugTagId;

    private List<AddDrugTag> mList;
    private AddDrugTagMulAdapter mAdapter;
    private AddDrugTagDialog addTagDrugDialog;

    public static AddDrugBaseFragment newInstance(int drugTagId,int drugId,int parentDrugTagId) {
        AddDrugBaseFragment fragment = new AddDrugBaseFragment();
        //如果有参数，使用Bundle传递
        Bundle bundle = new Bundle();
        bundle.putInt("drugTagId", drugTagId);
        bundle.putInt("drugId", drugId);
        bundle.putInt("parentDrugTagId", parentDrugTagId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected AddDrugBasePresenter createPresenter() {
        return new AddDrugBasePresenter(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_add_drug_base;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        etAddDrugName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                Log.e("TAG", "afterTextChanged: " + editable.toString());
                if (!TextUtils.isEmpty(editable.toString())) {
                    etAddDrugQrNamePy.setText(Cn2Py.getIndexPinYin(editable.toString()).replace(",", "").toUpperCase());
                } else {
                    etAddDrugQrNamePy.setText("");
                }

            }
        });
    }

    @Override
    protected void initData() {
        mList = new ArrayList<>();
        mAdapter = new AddDrugTagMulAdapter(R.layout.item_add_drug_tag,mList);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),5));
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if(mAdapter.getItem(position).isAddData){
                    addTagDrugDialog = new AddDrugTagDialog(MODE_TAG_ID,parentDrugTagId);
                    addTagDrugDialog.show(getFragmentManager(),"rvPackage");
                }else{
                    mAdapter.getItem(position).isSelect = !mAdapter.getItem(position).isSelect;
                    mAdapter.notifyItemChanged(position);
                }
            }
        });

        mAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if(!mAdapter.getItem(position).isAddData){
                    presenter.delSummaryTag(mAdapter.getItem(position).id);
                    mAdapter.remove(position);
                }
                return false;
            }
        });
        drugTagId = getArguments().getInt("drugTagId");
        drugId = getArguments().getInt("drugId");
        parentDrugTagId = getArguments().getInt("parentDrugTagId");


        presenter.getSummaryList(5, parentDrugTagId);
    }


    @OnClick(R.id.btn_add_drug_next)
    public void onViewClicked() {
        AddDrugReq drug = new AddDrugReq();
        drug.drug_id = drugId;
        drug.drug_tag = drugTagId;
        drug.barcode = etAddDrugQrCode.getText().toString();
        drug.drug_name = etAddDrugName.getText().toString();
        drug.company = etAddDrugQrFactory.getText().toString();
        drug.label_ids = getTagNameList();
        drug.parent_price = ConvertUtils.toDouble(etAddDrugPackagePrice.getText().toString());
        drug.sub_price = ConvertUtils.toDouble(etAddDrugMinPrice.getText().toString());

        if(TextUtils.isEmpty(drug.drug_name)){
            ToastUtil.showToast("请输入药品名称");
            return;
        }

        if(drug.parent_price == 0.00 || drug.sub_price == 0.00){
            ToastUtil.showToast("请输入药品价钱");
            return;
        }

        ((AddDrugActivity)getActivity()).setRadioGroupSelect();
        FragmentManager fm = getActivity().getSupportFragmentManager();
        Fragment fragment = ((AddDrugActivity)getActivity()).getDosageFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("addDrugReq",drug);
        bundle.putInt("drugTagId",drugTagId);
        bundle.putInt("drugId",drugId);
        bundle.putInt("parentDrugTagId",parentDrugTagId);
        fragment.setArguments(bundle);
        fm.beginTransaction().replace(R.id.fl_add_drug_container,fragment).commit();
    }

    @Override
    public void getTagSuccess(List<AddDrugTag> data) {
        data.add(new AddDrugTag(true));
        mAdapter.setNewInstance(data);
        if(drugId!=0){
            //不为0代表是查看、修改药品
            presenter.getDrugDetail(drugId);
        }
    }

    /**
     * 获取药品详情
     * @param drugDetail
     */
    @Override
    public void getDrugDetailSuccess(RespDrugDetail drugDetail) {
        etAddDrugQrCode.setText(drugDetail.barcode);
        etAddDrugName.setText(drugDetail.drug_name);
        etAddDrugQrFactory.setText(drugDetail.company);
        etAddDrugQrNamePy.setText(Cn2Py.getIndexPinYin(drugDetail.drug_name).replace(",", "").toUpperCase());

        etAddDrugPackagePrice.setText(String.valueOf(drugDetail.parent_price));
        etAddDrugMinPrice.setText(String.valueOf(drugDetail.sub_price));

        List<String> selectTag = drugDetail.label_ids;
        List<AddDrugTag> allTag = mAdapter.getData();
        for(int i=0;i<allTag.size();i++){
            for(int j=0;j<selectTag.size();j++){
                if(selectTag.get(j).equals(allTag.get(i).value)){
                    mAdapter.getItem(i).isSelect = true;
                }
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    //获取选中的药品标签
    public List<String> getTagNameList(){
        List<String> tagNameList = new ArrayList<>();
        List<AddDrugTag> tags =  mAdapter.getData();
        for(AddDrugTag tag: tags){
            if(tag.isSelect){
                tagNameList.add(tag.value);
            }
        }
        return tagNameList;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateData(UpdateAddTagEvent event) {
        presenter.getSummaryList(event.mode,parentDrugTagId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
